<template>
  <div class="topbar">
    <div class="wrap topbar-in">
      <!-- 左侧标题 -->
      <div class="topbar-l">欢迎来到叩丁狼积分商城</div>
      <!-- 右侧导航内容 -->
      <div class="topbar-r">
        <ul>
          <li @click="$router.push('/user')"><img :src="userInfo.headImg" class="avatar" alt="" />用户名：{{ userInfo.nickName }}</li>
          <li>我的积分：{{ userInfo.coin }}</li>
          <li>获取积分</li>
          <li>叩丁狼官网</li>
          <!-- <li class="car">购物车<em>5</em></li> -->

          <li class="cart-btn" v-if="isLogined" @click="$router.push('/user')">
            <img src="@/assets/images/cart.png" alt="" />
            <span>购物车</span>
            <strong>{{ cartTotal }}</strong>
          </li>
          <li v-else class="loginbtn" @click="changeIsShowLoginModal(true)">登录</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
import { WXLoginAPI } from '@/request/api'
export default {
  name: 'topbar',
  created() {
    // console.log('topbar-created')
    this.$router.onReady(async () => {
      // console.log('code值为：', this.$route.query.code)
      let pathcode = this.$route.query.code
      // 有code就发送微信扫码登录请求（把code给后端）
      if (pathcode) {
        let res = await WXLoginAPI(pathcode)
        // console.log('扫码登录', res)
        if (res.code == 0) {
          // 登录成功
          // 1.提示登录成功
          this.asyncChangeIsShowToast({
            isshow: true,
            msg: '微信扫码登录成功',
            type: 'success'
          })
          // 2.保存token
          localStorage.setItem('x-auth-token', res['x-auth-token'])
          // 3.改变登录状态true
          this.changeIsLogined(true)
          // 4.清除地址栏中code
          this.$router.push(this.$route.path)
          // 5.获取用户数据
          this.asyncChangeUserInfo()
        } else if (res.code == 400) {
          // 二维码失效
          // 1.提示用户二维码已经失效
          // alert('二维码失效了，请重新扫码！')
          this.asyncChangeIsShowToast({
            isshow: true,
            msg: '二维码失效了，请重新扫码！',
            type: 'danger'
          })
          // 2.引导用户再重新扫码
          this.changeIsShowLoginModal(true)
          // 地址栏中有code,并且code是错误就能重现。
        } else if (res.code == 407) {
          // 第一次访问项目，还没有绑定手机号
          // 1.提示用户再进行一次手机号登录--关联微信
          // alert('请使用手机号再登录一次')
          this.asyncChangeIsShowToast({
            isshow: true,
            msg: '请使用手机号再登录一次',
            type: 'warning'
          })
          // 2.打开登录模态框·引导用户登录
          this.changeIsShowLoginModal(true)
          // 3.先存储uuids
          localStorage.setItem('uuid', res.uuid)
          // 4.清除地址栏中code(避免扫码后地址栏code一直在，一刷新又重现发
          this.$router.push(this.$route.path)
        }
      } else {
        let token = localStorage.getItem('x-auth-token')
        this.changeIsLogined(Boolean(token))
        if (token) {
          // 已登录-重新发起请求，获取用户数据
          this.asyncChangeUserInfo()
        } else {
          // 未登录-还原用户信息
          this.initUserInfo()
        }
      }
    })
  },
  computed: {
    ...mapState({
      isLogined: (state) => state.loginStatus.isLogined,
      userInfo: (state) => state.userInfo.userInfo,
      cartTotal: (state) => state.userInfo.cartTotal
    })
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: 'showModal/changeIsShowLoginModal',
      changeIsLogined: 'loginStatus/changeIsLogined',
      initUserInfo: 'userInfo/initUserInfo'
    }),
    ...mapActions({
      asyncChangeIsShowToast: 'showToast/asyncChangeIsShowToast',
      asyncChangeUserInfo: 'userInfo/asyncChangeUserInfo'
    })
  }
  /* watch: {
    // 监听$route.path，更新登录状态
    '$route.path': {
      handler(newVal, oldVal) {
        let token = localStorage.getItem('x-auth-token')
        this.changeIsLogined(Boolean(token))
      }
    }
  } */
}
</script>

<style lang="less" scoped>
.topbar {
  height: 40px;
  line-height: 40px;
  background: #242b39;
  color: #fffefe;
  font-size: 14px;
  font-family: SourceHanSansSC;
  font-weight: 300;

  .topbar-in {
    display: flex;
    justify-content: space-between;

    .topbar-r {
      ul {
        display: flex;
        li {
          cursor: pointer;
          margin-left: 20px;
          text-align: center;
          &.loginbtn {
            width: 124px;
            height: 40px;
            background: #0a328e;
          }
          &.car {
            background: #0a328e;
            display: flex;
            justify-content: space-between;
            align-items: center;
            &::before {
              content: '';
              width: 20px;
              height: 19px;
              background-image: url('@/assets/images/cart.png');
              margin: 0 8px 0 14px;
            }
            em {
              content: '5';
              width: 22px;
              height: 22px;
              line-height: 22px;
              text-align: center;
              background: #fd604d;
              border-radius: 11px;
              margin: 0 12px 0 6px;
            }
          }
          &.cart-btn {
            width: 124px;
            height: 40px;
            background: #0a328e;
            text-align: center;
            img {
              width: 20px;
              height: 19px;
              vertical-align: middle;
            }
            span {
              margin: 0 8px;
            }
            strong {
              width: 22px;
              height: 22px;
              line-height: 22px;
              display: inline-block;
              border-radius: 50%;
              background-color: #fd604d;
            }
          }
          & > .avatar {
            width: 23px;
            height: 23px;
            border-radius: 50%;
            vertical-align: middle;
          }
        }
      }
    }
  }
}
</style>
